import { Permission } from '../../types';
import { PermissionRepository } from '../../repositories/system/PermissionRepository';
import { HttpError } from '../../exceptions/HttpError';
export class PermissionService {
  private permissionRepository: PermissionRepository;

  constructor() {
    this.permissionRepository = new PermissionRepository();
  }



  // // 获取所有菜单
  async getAllPermissions(): Promise<Permission[]> {
    try {
      return await this.permissionRepository.findAll();
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取权限列表失败: ${error.message}`);
    }
  }

  // // 根据ID获取用户
  async getPermissionById(id: string): Promise<Permission | null> {
    try {
      return await this.permissionRepository.findById(id);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取权限信息失败: ${error.message}`);
    }
  }

  // 创建用户
  async createPermission(permissionData: Partial<Permission>): Promise<Permission> {
    try {
      return await this.permissionRepository.create(permissionData);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`创建权限失败: ${error.message}`);
    }
  }

  // 更新菜单
  async updatePermission(id: string, permissionData: Partial<Permission>): Promise<Permission | null> {
    try {
      return await this.permissionRepository.update(id, permissionData);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`更新权限失败: ${error.message}`);
    }
  }

  // 删除菜单
  async deletePermission(id: string): Promise<boolean> {
    try {
      return await this.permissionRepository.delete(id);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`删除权限失败: ${error.message}`);
    }
  }



  // 获取权限数量
  async getPermissionCount(): Promise<number> {
    try {
      return await this.permissionRepository.count();
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`统计权限数量失败: ${error.message}`);
    }
  }

  // 分页查询菜单
  async getPermissionsWithPagination(page: number = 1, limit: number = 10): Promise<{ list: Permission[], total: number, pages: number }> {
    try {
      return await this.permissionRepository.findWithPagination(page, limit);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`分页查询权限失败: ${error.message}`);
    }
  }
}